<?php

class sp400Handler {

    private $_seed;
    private $_ti_host;
    private $_pwd;
    private $_account_no_arr;
    private $_number400;
    private $_last_error;
    private $_log;

    public function __construct() {
        
        $this->_seed = 'cali';
        $this->_ti_host = 'ipccs3.call4006.com';
        $this->_pwd = '55628383';
        $this->_account_no_arr = array('862900623', '862900624');
        $this->_number400 = array('6', '8');

        $this->_log = $GLOBALS['GLOBALS']['spConfig']['ext']['logger'];
        
    }
    

    public function GetLastError() {
        return $this->_last_error;
    }
    
    public function GetLastPhone( $uid){
        $db = spClass("cali_400");
        $info = $db->find(array('userid' => $uid));
        return array("phone" => $info['tophone'] , 'name' => $info['zname']);
        
    }
    
    public function CreateOrModifySeat( $uid , $phone , $name){
        
        $this->_log->addDebug("enter CreateOrModifySeat", func_get_args());
        $db = spClass("cali_400");
        $info400 = $db->find(array('userid' => $uid));
        if(!$info400){
            $this->_last_error = "用户未分配400电话队列";
            return false;
        }
        if( $info400['used'] == 0){
            $this->_last_error = "用户电话队列已被删除";
            return false;
        }
        
        //如果gid > 999 就用副帐号，副账户队列number gno = gid - 1000, 座席id必须大于2000，所以zid=gid+2000
        $gid = intval( $info400['gid']);
        if ( $gid > 999) {
            $account_no = $this->_account_no_arr[1];
            $gno = $gid - 1000;
        } else {
            $account_no = $this->_account_no_arr[0];
            $gno = $gid;
        
        }
        $cno = $gno + 2000;

        if($info400['zused'] == 0){
            $res = $this->cno("add" , $account_no, $cno , $phone, $name , $gno);
            if($res == '0'){
                $this->_log->addDebug("添加座席接口返回成功" , array("res" => $res));
                $res = $db->update( array('gid' => $gid) , array( 'zid' => $cno , 'zname' => $name, 'zused' => 1,'tophone' =>$phone));
                if($res){
                    $this->_log->addDebug("数据库写入成功" , array("data" => array('gid'=> $gid, 'zid' => $cno , 'zname' => $name, 'zused' => 1,'tophone' =>$phone)));
                    return true;
                }else{
                    $this->_last_error = "数据库写入失败";
                    $this->_log->addDebug("数据库写入失败" , array("data" => array('gid'=> $gid, 'zid' => $cno , 'zname' => $name, 'zused' => 1,'tophone' =>$phone)));
                }
            }else{
                $this->_log->addDebug("添加座席接口返回失败" , array("res" => $res));
                $this->_last_error = $res;
            }
        }else if ( $info400['zused'] == 1){
            $res = $this->cno("edit" , $account_no, $cno , $phone, $name , $gno);
            if($res == '0'){
                $this->_log->addDebug("修改座席接口返回成功" , array("res" => $res));
                $res = $db->update( array('gid' => $gid) , array( 'zid' => $cno , 'zname' => $name,'tophone' =>$phone));
                if($res){
                    $this->_log->addDebug("数据库写入成功" , array("data" => array('gid'=> $gid, 'zid' => $cno , 'zname' => $name,'tophone' =>$phone)));
                    return true;
                }else{
                    $this->_last_error = "数据库写入失败";
                    $this->_log->addDebug("数据库写入失败" , array("data" => array('gid'=> $gid, 'zid' => $cno , 'zname' => $name,'tophone' =>$phone)));
                }
            }else{
                $this->_log->addDebug("修改座席接口返回失败" , array("res" => $res));
                $this->_last_error = $res;
            }
        }
        
        return false;
        
    }
    
    public function DeleteSeat( $from_acc_num , $seat_id){
        $accountno = $this->_account_no_arr[$from_acc_num] ;
        
        $res = $this->cno("del", $accountno, $seat_id );
        if($res == '0'){
            return true;
        }else{
            return false;
        }

        
    }

    public function CreateGroup($uid) {
        $this->_log->addDebug("enter CreateGroup", func_get_args());
        $db = spClass("cali_user");
        $userinfo = $db->find(array('id' => $uid));
        if ($userinfo && $userinfo['state'] == 1) {
            
            $db = spClass("cali_400");
            $res = $db->find(array('userid' => $uid));
            if($res){
                $this->_log->addDebug("该uid已经创建过队列", array('res' => $res));
                return false;
            }
            
            if ($userinfo['utype'] == 3 or $userinfo['utype'] == 4) {
                $sql = "SELECT MIN( gid ) AS available_gid
                        FROM cali_400
                        WHERE used=0";
            } else {
                $sql = "SELECT MAX( gid ) AS available_gid
                        FROM cali_400
                        WHERE used =0";
            }
            $db = spClass("cali_400");
            $res = $db->findSql($sql);
            $gid = intval($res[0]['available_gid']);
            $this->_log->addDebug("get available_gid ", array("gid" => $gid));

            if ($gid > 999) {
                $account_no = $this->_account_no_arr[1];
                $gno = $gid - 1000;
                $number400 = $this->_number400[1];
            } else {
                $account_no = $this->_account_no_arr[0];
                $gno = $gid;
                $number400 = $this->_number400[0];
            }
            
            $groupname = $userinfo['id'];
            $groupname .=  '_' . date('Y-m-d');

            $res = $this->gno("add", $account_no, $gno, $groupname);
            if ($res == '0') {
                $data = array('used' => 1, '400number' => $number400,
                    'gname' => $userinfo['username'], 'userid' => $userinfo['id']);
                $this->_log->addDebug("成功新建队列，修改数据库", array("id" => $gid, "data" => $data));
                $res = $db->update(array("gid" => $gid), $data);
                $res = $this->_log->addDebug("修改数据库结果", array("res" => $res));
                if ($res) {
                    return true;
                } else {
                    $this->_last_error = "写入数据库失败";
                }
            } else {
                $this->_last_error = "添加队列失败，返回值=" . $res;
            }
        }

        return false;
    }

    //队列相关
    private function gno($action, $accountno, $gno, $groupname , $try = 2) {
        $this->_log->addDebug("enter gno function", func_get_args());

        $action_in = array('add', 'edit', 'del');
        $time = date('Y-m-d H:i');
        $this->_log->addDebug("time", array( 'time' => $time));

        $pwd = md5(md5($this->_pwd) . $this->_seed . $time);
        

        if (!in_array($action, $action_in)) {
            $result = '99';
        } else {
            if ($action == 'add') {
                $url = "http://" . "$this->_ti_host" . "/interface/newgroup.php?accountno=" . urlencode( $accountno) . "&pwd=" . $pwd . '&seed=' . $this->_seed . "&gno=" . $gno . "&groupname=" . $groupname . "&gtimeout=59";
                $r = file_get_contents($url);
                $result = $this->str_substr("<result>", "</result>", $r);
                
            } elseif ($action == 'edit') {
                $url = "http://" . "$this->_ti_host" . "/interface/editgroup.php?accountno=" . $accountno . "&pwd=" . $pwd . '&seed=' . $this->_seed . "&gno=" . $gno . "&groupname=" . $groupname. "&gtimeout=59";
                $r = file_get_contents($url);
                $result = $this->str_substr("<result>", "</result>", $r);
            } elseif ($action == 'del') {
                $url = "http://" . "$this->_ti_host" . "/interface/delgroup.php?accountno=" . $accountno . "&pwd=" . $pwd . '&seed=' . $this->_seed . "&gno=" . $gno;
                $r = file_get_contents($url);
                $result = $this->str_substr("<result>", "</result>", $r);
            } else {
                $result = '99';
            }
        }
        $this->_log->addDebug("get请求", array( 'url' => $url,'r' => $r));
        $this->_log->addDebug("队列操作返回值", array('res' => $result , 'try' => $try));
        $try = $try - 1;
        if( $result == '2' and $try > 0){
            sleep(3);
            $this->_log->addDebug("sleep 3 秒", array( 'try' => $try));
            $this->gno($action, $accountno, $gno, $groupname, $try);
        }
        
        return $result;
    }

    function cno($action, $accountno, $cno, $phone, $cnoname, $cnoqueue ,$try = 2) {
        $this->_log->addDebug("enter cno function", func_get_args());
        
        $action_in = array('add', 'edit', 'del');
        $time = date('Y-m-d H:i');
        
        $cnoqueue = sprintf("%03s",   $cnoqueue);
        $pwd = md5(md5($this->_pwd) . $this->_seed . $time);
        
        if ( !in_array($action, $action_in) ) {
            $result = '99';
        } else {
            if ($action == 'add') {
                $url = "http://" . $this->_ti_host . "/interface/newagent.php?accountno=" . $accountno . "&pwd=" . $pwd . "&seed=". $this->_seed . "&cno=" . $cno . "&cnoname=" . urlencode($cnoname) . "&cnotel=" . $phone . "&queue=" . $cnoqueue;
                $r = file_get_contents($url);
                $result = $this->str_substr("<result>", "</result>", $r);
            } elseif ($action == 'edit') {
                $url = "http://" . $this->_ti_host . "/interface/editagent.php?accountno=" . $accountno . "&pwd=" . $pwd . "&seed=". $this->_seed . "&cno=" . $cno . "&cnoname=" . $cnoname . "&cnotel=" . $phone . "&queue=" . $cnoqueue;
                $r = file_get_contents($url);
                $result = $this->str_substr("<result>", "</result>", $r);
            } elseif ($action == 'del') {
                $url = "http://" . $this->_ti_host . "/interface/delagent.php?accountno=" . "$accountno" . "&pwd=" . "$pwd" . "&seed=" . $this->_seed . "&cno=". "$cno";
                $r = file_get_contents($url);
                $result = $this->str_substr("<result>", "</result>", $r);
            } else {
                $result = '99';
            }
        }
        $this->_log->addDebug("get请求", array( 'url' => $url,'r' => $r));
        
        $this->_log->addDebug("座席操作返回值", array('res' => $result , 'try' => $try));
        $try = $try - 1;
        if( $result == '2' and $try > 0){
            sleep(3);
            $this->_log->addDebug("sleep 3 秒", array( 'try' => $try));
            $this->cno($action, $accountno, $cno, $phone, $cnoname, $cnoqueue ,$try);
        }
        return $result;
    }

    function str_substr($start, $end, $str) { // 字符串截取函数      
        $temp = explode($start, $str, 2);
        $content = explode($end, $temp[1], 2);
        return $content[0];
    }

}

?>
